<template>
  <el-dialog :title="title" :visible.sync="visible" width="80%" append-to-body v-dialogDrag="true" @close="handleClose">
    <el-form :model="form" ref="form" inline size="small" label-width="120px">
      <el-form-item label="地址" prop="address">
        <el-autocomplete
          popper-class="my-autocomplete"
          v-model="form.address"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入关键词搜索"
          :trigger-on-focus="false"
          :debounce="1000"
          @select="handleSelect"
        >
          <template slot-scope="{ item }">
            <div class="name">{{ item.name }}</div>
            <span class="addr">{{ item.address }}</span>
          </template>
        </el-autocomplete>
        <!-- <el-input
          v-model="form.address"
          placeholder="请输入地址"
          clearable
        /> -->
      </el-form-item>
      <div class="right-info" style="float: right;">
        <span style="margin-right: 8px;">{{ BD_LNG_LAT.join(',') }}</span>
        <el-button type="primary" icon="el-icon-delete-location" size="mini" @click="handleSearch()">确定</el-button>
      </div>
      
    </el-form>
    <div id="map" style="width: 100%; height: 70vh;"></div>
  </el-dialog>
</template>

<script>
import { bd09togcj02, gcj02towgs84, wgs84togcj02, gcj02tobd09 } from '@/utils/cooTrans'
  export default {
    name: 'TianDiTuMap',
    data() {
      return {
        visible: false,
        title: "地图",
        map: null,
        parentAddress: {
          address: '',
          lnglat: ''
        },
        form: {
          address: ''
        },
        lngLatStr: '',
        localsearch: '', // 搜索
        searchLists: [],
        showResult: false,
        BD_LNG_LAT: []
      }
    },
    props: {
      coord: {
        type: String,
        default: '115.966594,28.706100', // 传输值类型 都为BD09百度系
      }
    },
    mounted() {
    },
    methods: {
      // 地址搜索
      querySearchAsync(queryString, cb) {
        this.localsearch.search(queryString, 4)
        let interval = setInterval(() => {
          if (this.showResult) {
            clearInterval(interval)
            this.showResult = false
            cb(this.searchLists)
          }
        }, 1000);
      },
      handleSelect(val) {
        this.form.address = val.name
        const lnglat = val.lonlat.split(',')
        this.map.panTo(new T.LngLat(lnglat[0], lnglat[1]), 18);
        this.handleDragEvent(lnglat[0], lnglat[1])
      },
      openDialog(data) {
        this.parentAddress = {
          address: data?.address || '',
          lnglat: data?.lnglat
        }
        this.visible = true
        this.$nextTick(() => {
          this.initMap();
        })
      },
      handleSearch() {
        this.$emit('confirm', this.BD_LNG_LAT)
        this.form.address = ''
        this.visible = false
      },
      async initMap() {
        let that = this
        
        if (!this.map) {
          var zoom = 18
          this.map = new T.Map("map", {
              projection: 'EPSG:4326'
          });
        }
        // 获取默认地址
        
        let lnglat = this.parentAddress.lnglat
        let addressStr = this.parentAddress.address
        let address;
        if (lnglat[0] && lnglat[1]) {
          address = lnglat
        } else if (addressStr) {
          let { lng, lat } = await this.addressToLng(addressStr)
          const gcjCoord = wgs84togcj02(lng, lat)
          const bd09Coord = gcj02tobd09(gcjCoord[0], gcjCoord[1])
          address = [bd09Coord[0], bd09Coord[1]]
        } else {
          address = this.coord.split(',')
        }


        const gcjCoord = bd09togcj02(address[0],address[1])
        const wgsCoord = gcj02towgs84(gcjCoord[0], gcjCoord[1])

        this.map.centerAndZoom(new T.LngLat(wgsCoord[0],wgsCoord[1]), zoom);

        this.map.addEventListener("click", function(e){
          let lng = e.lnglat.getLng()
          let lat = e.lnglat.getLat()
          that.handleDragEvent(lng, lat)
        });

        var config = {
            pageCapacity: 10,	//每页显示的数量
            onSearchComplete: function(result) {
              that.showResult = true
              that.searchLists = result.getSuggests()
            }	//接收数据的回调函数
        };
        //创建搜索对象
        this.localsearch = new T.LocalSearch(this.map, config);

        // 判断是否存在经纬度，没有经纬度使用地址   否则默认地址
        if (lnglat[0] && lnglat[1]) {
          this.handleDragEvent(wgsCoord[0], wgsCoord[1])
        } else {
          this.handleDragEvent()
        }

        
      },
      // 
      handleClose() {
        // this.map.clearOverLays()
        // this.map = null
      },
      // 根据经纬度获取地址
      async getGeocoderFun(lon, lat) {
        return new Promise((resolve, reject) => {
          let T = window.T;
          let geocoder = new T.Geocoder();
          geocoder.getLocation(new T.LngLat(lon, lat), (result) => {
            resolve({
              address: result.getAddress(),
              addressComponent: result.getAddressComponent(),
            })
          });
        })
      },
      // 根据地址获取经纬度
      async addressToLng(address) {
        let geocoder = new T.Geocoder();
        return new Promise((resolve, reject) => {
          this.map.clearOverLays();
		      geocoder.getPoint(address, function(result) {
            if(result.getStatus() == 0){
              console.log(result.getLocationPoint());
              resolve({
                lng: result.getLocationPoint().getLng(),
                lat: result.getLocationPoint().getLat(),
              })
              // this.map.panTo(result.getLocationPoint(), 16);
            }else{
              reject(result.getMsg());
            }
          });
        })
      },
      // 获取中心点 添加标注 地图拖动事件
      handleDragEvent(lng, lat) {
        let that = this
        this.map.clearOverLays()
        // 获取中心点
        
        lng = lng || this.map.getCenter().getLng()
        lat = lat || this.map.getCenter().getLat()

        // 转换为百度类型点位
        const gcjCoord = wgs84togcj02(Number(lng), Number(lat))
        const bd09Coord = gcj02tobd09(gcjCoord[0], gcjCoord[1])
        this.BD_LNG_LAT = [bd09Coord[0].toFixed(6),bd09Coord[1].toFixed(6)]
        console.log(gcjCoord, `${lng},${lat}`, `${bd09Coord[0]},${bd09Coord[1]}`);

        this.getGeocoderFun(lng,lat).then(res => {
          const { address, addressComponent } = res

          //创建标注对象
          this.marker = new T.Marker(new T.LngLat(lng, lat));
          that.map.addOverLay(this.marker);

          let infoWindow = new T.InfoWindow(`地址：${address}<br/>距离最近：${addressComponent.poi}<br/>坐标：${lng},${lat}<br/>`);
          this.marker.openInfoWindow(infoWindow, new T.LngLat(lng,lat));
          this.marker.enableDragging();


          this.marker.removeEventListener("dragstart", this.dragStart);
          this.marker.removeEventListener("dragend", this.dragEnd);
          this.marker.addEventListener("dragstart", this.dragStart);
          this.marker.addEventListener("dragend", this.dragEnd);

          that.lngLatStr = `${lng},${lat}`
        })
      },
      dragStart(e) {
        
        console.log(e);
        
      },
      dragEnd(e) {
        let lng = e.lnglat.getLng()
        let lat = e.lnglat.getLat()

        this.handleDragEvent(lng, lat)
      }
    }
  }
</script>

<style lang='scss' scoped>
.my-autocomplete {
  li {
    line-height: normal;
    padding: 7px;

    .name {
      text-overflow: ellipsis;
      overflow: hidden;
    }
    .addr {
      font-size: 12px;
      color: #b4b4b4;
    }

    .highlighted .addr {
      color: #ddd;
    }
  }
}
</style>